package droid.frame.view.xlist;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

public class SListView extends ListView implements OnScrollListener {

	private FooterLayout mFooter;
	private FooterListener mFooterListener;
	private boolean mLastItemVisible;
	private Context context;

	public SListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		this.setOnScrollListener(this);

	}

	public void setFooterListener(FooterListener footerListener) {
		// 下滑需要用到
		this.mFooterListener = footerListener;
	}

	/**
	 * 更新Footer
	 * 
	 * @param currentPage
	 * @param totalPage
	 */
	public void updateFooter(int currentPage, int totalPage) {
		if (totalPage >= currentPage && totalPage > 1) {
			if (mFooter == null) {
				mFooter = new FooterLayout(context);
				this.addFooterView(mFooter);
			}
			mFooter.setVisibility(View.VISIBLE);
		} else {
			if (mFooter != null) {
				mFooter.setVisibility(View.GONE);
			}
		}
		if (mFooter != null) {
			mFooter.setFooterText(currentPage, totalPage, true);
			// 单击需要用到
			this.mFooter.setFooterListener(this.mFooterListener);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		/**
		 * Check that the scrolling has stopped, and that the last item is visible.
		 */
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && null != mFooterListener && mLastItemVisible) {
			if (mFooter != null) {
				mFooter.setVisibility(View.VISIBLE);
			}
			if (mFooterListener != null) {
				mFooterListener.onFooterVisible();
			}
		}

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (null != mFooterListener) {
			mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
		}
	}

}
